﻿using Ardalis.ApiEndpoints;
using Microsoft.AspNetCore.Mvc;
using TodoList.ArdalisEndpoints.DTOs;
using TodoList.ArdalisEndpoints.Mapper;
using TodoList.Data;

namespace TodoList.ArdalisEndpoints.Endpoints.TodoList;

public class Update(ApplicationDbContext db) : EndpointBaseAsync
	.WithRequest<UpdateTodoItemRequest>
	.WithActionResult
{
	[HttpPut("api/[namespace]/{id:int}")]
	public override async Task<ActionResult> HandleAsync([FromMultiSource]UpdateTodoItemRequest request, CancellationToken cancellationToken = default)
	{
		var item = await db.TodoItems.FindAsync(request.Id, cancellationToken);
		if (item == null)
		{
			return NotFound("Todo item not found.");
		}
		item.UpdateEntity(request);
		await db.SaveChangesAsync(cancellationToken);
		return Ok("Todo item updated successfully.");
	}
}
